package associationrules;

import java.util.HashMap;
import java.util.Map;

import static util.Preconditions.check;

/**
 * 
 * Solves the association rules problem sequentially
 *
 */
public class AssociationRules {
	
	private long minOccurrences;
	private int size;
	
	public AssociationRules(long minOccurrences, int size) {
		check(minOccurrences > 0, "minOccurrences must be positive");
		check(size > 0, "size must be positive");
		
		this.minOccurrences = minOccurrences;
		this.size = size;
	}

	public Map<String, Long> rules(String source) {
		Map<String, Long> rules = new HashMap<String, Long>();
		
		int start = 0;
		int end = start + size;
		
		while (end <= source.length()) {
			countOccurrence(source, rules, start, end);
			start++;
			end++;
		}
		
		extractLessPopularRules(rules);
		return rules;
	}

	private void countOccurrence(String source, Map<String, Long> rules,
			int start, int end) {
		String nextSubstring = source.substring(start, end);
		if (!rules.keySet().contains(nextSubstring)) {
			rules.put(nextSubstring, 0L);
		}
		rules.put(nextSubstring, rules.get(nextSubstring) + 1);
	}

	private void extractLessPopularRules(Map<String, Long> rules) {
		for (String key : rules.keySet()) {
			if (rules.get(key) < minOccurrences) {
				rules.put(key, null);
			}
		}
	}
}
